package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import ejb.ApplyFacadeEJBRemote;
import ejb.LikeFacadeEJBRemote;
import ejb.TagFacadeEJBRemote;
import ejb.TargetFacadeEJBRemote;
import ejb.UserFacadeEJBRemote;


import model.Mycomment;
import model.Myuser;
import model.Tag;
import model.Target;

/**
 * Servlet implementation class TargetServlet
 */
@WebServlet("/TargetServlet")
public class TargetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@PersistenceUnit
	EntityManagerFactory emf;
    
    @Resource private UserTransaction utx;
    
	@PersistenceContext
	EntityManager em;
	
    @EJB ApplyFacadeEJBRemote af;
    @EJB LikeFacadeEJBRemote lf;
    @EJB UserFacadeEJBRemote uf;
    @EJB TagFacadeEJBRemote tf;
    @EJB TargetFacadeEJBRemote targetf;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TargetServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    
    public static boolean checkStrIsInt(String s){
        String temp = s;
        if(s.length()==0){
            return false;
        }
        int l = s.length();
        for(int i=0;i<l;i++){
            if(!Character.isDigit(temp.charAt(i))){
                return false;
            }
        }
        return true;
    }

    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		boolean l;
		String liked = "";
		Myuser u = new Myuser();
		Target t = new Target();
		
		PrintWriter out = response.getWriter();
		
		HttpSession session=request.getSession();
        
		response.setContentType("text/html;charset=UTF-8");
		
		String tid = (String)request.getParameter("targetID");
		
		String merchantinfo = (String)request.getParameter("merchantinfo");
		
		String tid2 = (String)request.getParameter("tid2");
		
		String username = (String)session.getAttribute("username");
		
		
		
		
		String liketargetid = (String)request.getParameter("keyword");
		
		String applytargetid = (String)request.getParameter("targetid");
	
		String reason = (String)request.getParameter("applyform");
		
		String closetargetid = (String)request.getParameter("closeTID");
		
		String opentargetid = (String)request.getParameter("openTID");
		
		String tagtid = (String)request.getParameter("tagtid");
		
		String tag = (String)request.getParameter("tag");
		if(username==null){
			response.sendRedirect("home.jsp");    
			}
		else{
		
		try{
			utx.begin();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		
		//tag not exist
				if(tf.ifTagExist(tag)==false && tagtid!=null && tag!=null){
					
					if(checkStrIsInt(tagtid)==false){
					t.setTargetid(-1);
					}else{
				
					//create tag
					tf.createTag(tag);
					Tag justAddedTag = tf.queryTagByName(tag);
					
					int tagid = Integer.parseInt(tagtid);
					t = targetf.queryByTargetID(tagid);
					u= uf.findUserByName(username);
					
					if(tf.ifTargetTagExist(t, justAddedTag)==false){
						tf.createTargetTag(u, t, justAddedTag);
					}
					
					l = lf.ifLikeExist(u, t);
					if(l==true){
						liked = "true";
					}else{
						liked = "false";
					}
					}
					
				}// tag already exist
				else if(tf.ifTagExist(tag)==true && tagtid!=null && tag!=null){
					
					if(checkStrIsInt(tagtid)==false){
					t.setTargetid(-1);
					}else{
				
					
					Tag existTag = tf.queryTagByName(tag);
					int tagid = Integer.parseInt(tagtid);
					
					t = targetf.queryByTargetID(tagid);
					u= uf.findUserByName(username);
					
					//targetTag already exist in the target
					if(tf.ifTargetTagExist(t, existTag)==true){
						
						l = lf.ifLikeExist(u, t);
						if(l==true){
							liked = "true";
						}else{
							liked = "false";
						}
					}
					//targetTag not exist but tag exist
					else{
						Tag hasTag = tf.queryTagByName(tag);
						t = targetf.queryByTargetID(tagid);
						u= uf.findUserByName(username);
						
						tf.createTargetTag(u, t, hasTag);
						l = lf.ifLikeExist(u, t);
						
						if(l==true){
							liked = "true";
						}else{
							liked = "false";
						}
					}
					
					}
				}
		
		if(opentargetid!=null){
			
			if(checkStrIsInt(opentargetid)==false){
			t.setTargetid(-1);
			}
			else{
			
			try{
				
				int openid = -1;
				
				openid = Integer.parseInt(opentargetid);
				if(targetf.checkIfExistByID(openid)==false){
					t.setTargetid(-1);
				}
				
				else{
					t=targetf.queryByTargetID(openid);
					u= uf.findUserByName(username);
					t.setActivestatus(1);
					em.merge(t);
				
					l = lf.ifLikeExist(u, t);
					if(l==true){
						liked = "true";
					}else{
						liked = "false";
					}
				}
			}
			catch(Exception e){
			}
			}
		}
		
		
		if(closetargetid!=null){
			
			
			if(checkStrIsInt(closetargetid)==false){
			t.setTargetid(-1);
			}else{
			try{
				int closetid = -1;
				closetid = Integer.parseInt(closetargetid);
				
				if(targetf.checkIfExistByID(closetid)==false){
					t.setTargetid(-1);
				}
				else{
					t=targetf.queryByTargetID(closetid);
					u= uf.findUserByName(username);
					t.setActivestatus(0);
					em.merge(t);
				
					l = lf.ifLikeExist(u, t);
					if(l==true){
						liked = "true";
					}else{
						liked = "false";
					}
				}
			}
			catch(Exception e){
			}
			}
		}
		
		
		if(tid!=null){
			
			
			if(checkStrIsInt(tid)==false){
				t.setTargetid(-1);
			}else{
			try {
                int targetid = -1;
				targetid = Integer.parseInt(tid);

                if(targetf.checkIfExistByID(targetid)==false){
					t.setTargetid(-1);
				}
				else{
                
					t= targetf.queryByTargetID(targetid);
				
					u= uf.findUserByName(username);
                
					l = lf.ifLikeExist(u, t);
					if(l==true){
						liked = "true";
					}else{
						liked = "false";
					}
				}
	        } catch (Exception e) {
	        }
			}
		}
		
		
		if(applytargetid!=null && reason!=null){
			
			
			if(checkStrIsInt(applytargetid)==false){
				t.setTargetid(-1);
			}
			else{
			
			int applytid = -1;
			applytid = Integer.parseInt(applytargetid.trim());
			
			if(targetf.checkIfExistByID(applytid)==false){
				t.setTargetid(-1);
			}
			else{
			
				u = uf.findUserByName(username);
				t = targetf.queryByTargetID(applytid);
            
				if(af.ifApplyExist(u, t)==false){
					af.createApply(u, t, reason, "waiting");
				}
            
				l = lf.ifLikeExist(u, t);
				if(l==true){
					liked="true";
				}else{
					liked="false";
				}
			}
			}
		}
		
		
		if(liketargetid!=null){
			u= uf.findUserByName(username);
			if(checkStrIsInt(liketargetid)==false){
				t.setTargetid(-1);
			}
			else{
				int liketid = -1;
				liketid = Integer.parseInt(liketargetid);
				
				if(lf.ifLikeExist2(u.getUsername(), liketid)==true || targetf.checkIfExistByID(liketid)==false){
					t.setTargetid(-1);
				}
				else{
					t = targetf.queryByTargetID(liketid);
					u = uf.findUserByName(username);
					lf.createLike(u, t);
					liked = "true";
				}
			}
		}
        
		
		if(merchantinfo!=null){
			
			if(tid2==null || checkStrIsInt(tid2)==false){
				t.setTargetid(-1);
			}else{
			try{
                
				int targetid = -1;
				targetid = Integer.parseInt(tid2);

				Target tempT = targetf.queryByTargetID(targetid);
				Myuser tempU = uf.findUserByName(username);
				
				if(targetf.checkIfExistByID(targetid)==false || !tempT.getMyuser().getUsername().equals(username)){
					t.setTargetid(-1);
				}else{
					
					if(!tempU.getUsername().equals( tempT.getMyuser().getUsername())){
						t.setTargetid(-1);
					}
					else{
						t= targetf.queryByTargetID(targetid);
						t.setMchtinfo(merchantinfo);
						//insert merchant info
						em.merge(t);
						u= uf.findUserByName(username);
						l = lf.ifLikeExist(u, t);
						if(l==true){
							liked = "true";
						}else{
							liked = "false";
						}
					}
				}
			}
			catch(Exception e){
			}
			}
		}
		
		try{
			utx.commit();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
        String url="";
		
		if(targetf.checkIfExistByID(t.getTargetid())==false){
			out.print("Please access this page via normal way...");
			url="Error404.jsp";
		}else{
			List<Mycomment> comments=null;
			comments=targetf.getCommentOfTarget(t);
			List<Tag> tag_list = tf.getTagListByTarget(t);
			request.setAttribute("comments", comments);
			request.setAttribute("taglist", tag_list);
			request.setAttribute("liked", liked);
			request.setAttribute("return_t", t);
			url="Target.jsp";
		}
		
		request.getRequestDispatcher(url).forward(request, response);
		}
	}
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
    
}


